package com.ideabove.radio;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.gcm.GCMRegistrar;
import com.ideabove.network.NetWorkManager;
import com.ideabove.radio.R;
import com.ideabove.radio.module.FacebookMd;
import com.ideabove.radio.module.FacebookMd.FacebookCallback;
import com.ideabove.radio.module.FolderDetailMd;
import com.ideabove.radio.module.FolderEditMd;
import com.ideabove.radio.module.FolderMd;
import com.ideabove.radio.module.GenreMd;
import com.ideabove.radio.module.ModuleInterface;
import com.ideabove.radio.module.NotificationMd;
import com.ideabove.radio.module.SongEditMd;
import com.ideabove.radio.module.SongInsertMd;
import com.ideabove.radio.module.SongSearchMd;
import com.ideabove.radio.module.UserProfileEditMd;
import com.ideabove.radio.module.UserProfileMd;
import com.ideabove.radio.service.PlayBackService;
import com.ideabove.radio.service.PlayBackService.MediaPlayerSingleton;
import com.ideabove.adapter.CommentAdapter;
import com.ideabove.custom.MyMediaController;
import com.ideabove.custom.MyVideoView;
import com.ideabove.data.Comment;
import com.ideabove.data.PlayItem;
import com.ideabove.db.ImageDBHelper;
import com.ideabove.util.ConnectThread;
import com.ideabove.util.Connectivity;
import com.ideabove.util.UniqueDeviceID;
import com.ideabove.util.kakao.KakaoUtil;
//import com.joyhub.askname.DeviceUniqueID;
//import com.joyhub.askname.JoyhubAPI;
//import com.joyhub.askname.JoyhubWebview;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.content.res.Configuration;
import android.graphics.PorterDuff.Mode;

@SuppressLint({ "ShowToast", "ShowToast", "ShowToast", "ShowToast" })
public class MainActivity extends Activity implements OnCompletionListener,
		OnClickListener, MediaPlayer.OnPreparedListener,
		MyVideoView.OnBufferingUpdateListener, MyVideoView.OnInfoListener,
		MediaPlayer.OnErrorListener, OnSeekCompleteListener,
		MyMediaController.MediaControllerToggleListener {

	// private String LINK =
	// "http://o-o---preferred---sn-ogueyn7s---v11---lscache1.c.youtube.com/videoplayback?upn=t4Kq1usLQpI&el=related&sparams=cp,id,ip,ipbits,itag,ratebypass,source,upn,expire&fexp=908920,906361,916616,901447,922401,920704,912806,927201,925003,913546,913556,916805,920201,900816,911112,901451&ms=au&dnc=1&itag=18&ipbits=8&app=youtube_mobile&signature=AD7E182E3D8B11020C7DC6DBCD63870C9E8A554E.2A4CD17843BC9940C4494EE69C52B31EDB374098&mv=m&yms=pUNSQd0e0R4&sver=3&mt=1352270110&ratebypass=yes&source=youtube&expire=1352293748&key=yt1&ip=114.71.50.170&cp=U0hUR1JUUV9JUkNONF9KTlVIOnRSTVRPYjdkNVIw&id=59960554c5581bc9";

	private static final boolean DEVELOPER_MODE = false;
	public static String PUSH_PROJECT_ID = "385944709898";

	Thread m_GetDataThread = null;
	Thread m_PlayThread = null;
	Thread m_CommentThread = null;

	private ProgressBar m_LoadingProgress = null;
	TextView video_title = null;
	TextView video_owner = null;
	// TextView video_link_cnt = null;
	TextView video_desc = null;
	ListView video_comments = null;
	// LinearLayout studio_layout = null;
	LinearLayout video_info_wrap = null;
	ImageView list_comment_underline = null;
	public Activity mActivity = null;
	public int mOrientation = 1;

	// module
	public Toast toast = null;
	public GenreMd genreMd = new GenreMd();
	public FolderMd folderMd = new FolderMd();
	public FolderEditMd folderEditMd = new FolderEditMd();
	// public ChannelMd channelMd = new ChannelMd();
	public FacebookMd facebookMd = new FacebookMd();
	public NotificationMd noticeMd = new NotificationMd();
	public UserProfileMd userProfileMd = new UserProfileMd();
	public FolderDetailMd folderDetailMd = new FolderDetailMd();
	public SongEditMd songEditMd = new SongEditMd();
	public SongSearchMd songSearchMd = new SongSearchMd();
	public SongInsertMd songInsertMd = new SongInsertMd();
	public UserProfileEditMd userProfileEditMd = new UserProfileEditMd();

	// db
	ImageDBHelper imgDBHelper = new ImageDBHelper(this);

	// 현재 플레이 리스트
	PlayItem mCurplayItem;

	// 모듈을 관리한다.
	ModuleInterface mCurMoudle = null;

	public void setCurrentMoudle(ModuleInterface moudle) {
		
		this.mCurMoudle = moudle;
	}

	// joyhub
//	public static JoyhubAPI g_joyhub;
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_main);
		doBindService();
		mActivity = this;

//		Intent intent = new Intent(this, DeviceUniqueID.class);
//		startActivityForResult(intent, 0);

		// Get memory class of this device, exceeding this amount will throw an
		// OutOfMemory exception.
		final int memClass = ((ActivityManager) getApplicationContext()
				.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();

		// Use 1/8th of the available memory for this memory cache.
		final int cacheSize = 1024 * 1024 * memClass / 8;

		try {
			PackageInfo info = getPackageManager().getPackageInfo(
					"com.ideabove.radio", PackageManager.GET_SIGNATURES);
			for (Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				Log.e("KeyHash:",
						Base64.encodeToString(md.digest(), Base64.DEFAULT));
			}
		} catch (NameNotFoundException e) {

		} catch (NoSuchAlgorithmException e) {

		}

		init();

		// facebook
		facebookMd.init(this);
		facebookMd.onCreate(savedInstanceState);

	}

	public void kakaoPlay() {
		// last kakaotalk play
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			String query = (String) bundle.get("q");
			// Log.e("########", "###QQQ###" + query);
			// Log.e("########", "######" + bundle.getString("cid"));
			// Log.e("########", "######" + bundle.getString("link"));
			// Log.e("########", "######" + query);

			if (!TextUtils.isEmpty(query)) {
				Message msg = Message.obtain(null,
						PlayBackService.REQUEST_MSG_GET_TEMP_VIDEO_TO_PLAY);
				PlayItem pItem = new PlayItem();
				pItem.setCpost_id(bundle.getString("cid"));
				pItem.setLink(bundle.getString("link"));
				msg.obj = pItem;
				mCurplayItem = pItem;
				sendMessageToService(msg);

				if (mCurMoudle != null) {
					mCurMoudle.hide();
				}

			}
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		facebookMd.onActivityResult(requestCode, resultCode, data);
//		Log.d("TAG", "requestCode :: " + requestCode);
//		if (requestCode == 0)
//		{
//			if (resultCode == RESULT_OK) {
//				String strDeviceID = data.getStringExtra("DeviceID");
//				g_joyhub = new JoyhubAPI(this.getPackageName(),strDeviceID,this);
//				g_joyhub.initAPI();
//				
//				JoyhubAPI.onUpdateUserPointFinishCallback callback =
//					new JoyhubAPI.onUpdateUserPointFinishCallback() {
//					public void onUpdateUserPointFinish() {
//						Log.d("joyhub", "onUpdateUserPointFinish callback called");
//					}
//				};
//				g_joyhub.setUpdateUserPointFinishCallback(callback);
//				g_joyhub.UpdateUserPoint();
//			}
//		}
	}

	@Override
	public void onStart() {
		super.onStart();
		// The rest of your onStart() code.
		EasyTracker.getInstance().activityStart(this); // Add this method.
	}

	@Override
	public void onStop() {
		super.onStop();
		PlayBackService.isRunningApp = false;
		imgDBHelper.close();
		// The rest of your onStop() code.
		EasyTracker.getInstance().activityStop(this); // Add this method.
	}

	public void initDB() {
		imgDBHelper.open();
	}

	public void initPushService() {
		// 디바이스 GCM 사용 가능한지 확인
		// GCMRegistrar.checkDevice(this);
		// // 매니페스트 설정이 올바른지 확인
		// GCMRegistrar.checkManifest(this);
		// // 등록
		// registerToken();

	}

	/**
	 * GCM에 디바이스 토큰 등록
	 */
	private void registerToken() {
		// registration ID（디바이스 토큰) 취득하고 등록되지 않은 경우 GCM에 등록
		String regId = GCMRegistrar.getRegistrationId(this);

		if ("".equals(regId)) {
			GCMRegistrar.register(this, PUSH_PROJECT_ID);
		}
	}

	/**
	 * GCM에 디바이스토큰 삭제
	 */
	private void unregisterToken() {
		// if (GCMRegistrar.isRegistered(this)) {
		// GCMRegistrar.unregister(this);
		// }
	}

	public void init() {

		initDB();
		initPushService();
		// studio_layout = (LinearLayout) findViewById(R.id.studio_layout);
		playerInit();
		commonInit();

		// module
		noticeMd.init(this);
		// channelMd.init(this);
		folderMd.init(this);
		folderEditMd.init(this);
		folderDetailMd.init(this);
		userProfileMd.init(this);
		songEditMd.init(this);
		songSearchMd.init(this);
		songInsertMd.init(this);
		userProfileEditMd.init(this);

		genreMd.init(this);
		genreMd.showGenreList();

		// 상단바 클릭
		ImageView img_genre_top = (ImageView) findViewById(R.id.img_genre_top);
		img_genre_top.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				ImageView view = (ImageView) v;
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					view.setPadding(2, 2, 2, 2);
					view.setColorFilter(0xaa111111, Mode.SRC_OVER);
				} else if (event.getAction() == MotionEvent.ACTION_UP) {

					if (mCurMoudle != null) {
						if (mCurMoudle.isVisible()) {
							mCurMoudle.hide();
						} else {
							mCurMoudle.show();
						}
					} else {
						genreMd.showGenreList();
					}

					view.setPadding(0, 0, 0, 0);
					view.setColorFilter(0x00000000, Mode.SRC_OVER);
				} else {
					view.setPadding(0, 0, 0, 0);
					view.setColorFilter(0x00000000, Mode.SRC_OVER);
				}

				return true;
			}
		});

		m_LoadingProgress = (ProgressBar) findViewById(R.id.vodplayer_loading_progress);
		PlayBackService.MediaPlayerSingleton.reset();

	}

	public void commonInit() {

		// studio button click
		ImageView btn_top_right_img = (ImageView) findViewById(R.id.btn_top_right_img);
		btn_top_right_img.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {

				// TODO Auto-generated method stub
				if (event.getAction() == MotionEvent.ACTION_UP) {
					// ViewFlipper myViewFlipper =
					// (ViewFlipper)findViewById(R.id);
					// AnimationFactory.flipTransition(myViewFlipper,
					// FlipDirection.RIGHT_LEFT);

					displayStudio();
				}

				return true;
			}
		});
	}

	public void displayStudio() {

		// fb login check
		if (!facebookMd.isActiveSession()) { // no facebook login
			facebookMd.showLoginPage(new FacebookCallback() {

				@Override
				public void callback() {
					// TODO Auto-generated method stub
					SharedPreferences prefs = getSharedPreferences(
							FacebookMd.PREFERENCE_USER_KEY,
							Activity.MODE_PRIVATE);
					String fbId = prefs.getString(
							FacebookMd.PREFERENCE_USER_FB_ID, "");
					String fbFirstNm = prefs.getString(
							FacebookMd.PREFERENCE_USER_FB_FIRST_NM, "");
					String fbLastNm = prefs.getString(
							FacebookMd.PREFERENCE_USER_FB_LAST_NM, "");
					String email = prefs.getString(
							FacebookMd.PREFERENCE_USER_FB_LAST_EMAIL, "");
					facebookMd.requestGetUserId(fbId, fbFirstNm, fbLastNm,
							email, new FacebookMd.RequestCallback() {
								@Override
								public void callback(String msg) {
									// TODO Auto-generated method stub
									if ("genreno".equals(msg)) { // 장르가
																	// 아직...세팅안된
																	// 회원
										userProfileMd
												.setProfileSavedCallback(new UserProfileMd.UserProfileCallback() {
													@Override
													public void callback() {
														userProfileMd
																.hideUserProfile();
														folderMd.showFolderList();
													}
												});
										facebookMd.hideLoginPage();
										userProfileMd.showUserProfile();

									} else { // 기존회원

										facebookMd.hideLoginPage();
										folderMd.showFolderList();
									}

								}
							});
				}
			});

		} else if (facebookMd.isActiveSession()
				&& facebookMd.getBonoUserId().length() < 1) { // facebook login
																// but no userid
			SharedPreferences prefs = getSharedPreferences(
					FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE);
			String fbId = prefs.getString(FacebookMd.PREFERENCE_USER_FB_ID, "");
			String fbFirstNm = prefs.getString(
					FacebookMd.PREFERENCE_USER_FB_FIRST_NM, "");
			String fbLastNm = prefs.getString(
					FacebookMd.PREFERENCE_USER_FB_LAST_NM, "");
			String email = prefs.getString(
					FacebookMd.PREFERENCE_USER_FB_LAST_EMAIL, "");

			facebookMd.requestGetUserId(fbId, fbFirstNm, fbLastNm, email,
					new FacebookMd.RequestCallback() {

						@Override
						public void callback(String msg) {
							// TODO Auto-generated method stub
							String userId = facebookMd.getBonoUserId();
							if (userId == null || userId.length() < 1) {
								// 기존회원인데 장르 세팅 안된 회원
								userProfileMd
										.setProfileSavedCallback(new UserProfileMd.UserProfileCallback() {
											@Override
											public void callback() {
												userProfileMd.hideUserProfile();
											}
										});
								userProfileMd.showUserProfile();
							} else {
								// 기존회원
								folderMd.showFolderList();

							}

						}
					});

		} else { // having ids
			folderMd.showFolderList();
		}
	}

	public void playerInit() {
		// Player
		ImageView player_btn_pre = (ImageView) findViewById(R.id.player_btn_pre);
		player_btn_pre.setOnTouchListener(videoPreviewListener);
		ImageView player_btn_next = (ImageView) findViewById(R.id.player_btn_next);
		player_btn_next.setOnTouchListener(videoNextListener);
		ImageView player_btn_play_pause = (ImageView) findViewById(R.id.player_btn_play_pause);
		player_btn_play_pause.setOnTouchListener(videoPauseListener);
		ImageView player_like_btn = (ImageView) findViewById(R.id.player_like_btn);
		player_like_btn.setOnTouchListener(videoLike);

		ImageView img_genre_top = (ImageView) findViewById(R.id.img_genre_top);
		img_genre_top.setOnTouchListener(topTouchListener);

		FrameLayout video_wrap = (FrameLayout) findViewById(R.id.video_wrap);
		video_wrap.setOnClickListener(this);

		// videoInfo
		video_title = (TextView) findViewById(R.id.video_title);
		video_owner = (TextView) findViewById(R.id.video_owner);
		video_owner.setOnTouchListener(videoOwnerTouchListener);

		// video_link_cnt = (TextView) findViewById(R.id.video_link_cnt);
		video_desc = (TextView) findViewById(R.id.video_desc);
		video_comments = (ListView) findViewById(R.id.list_comment);
		video_info_wrap = (LinearLayout) findViewById(R.id.video_info_wrap);
		list_comment_underline = (ImageView) findViewById(R.id.list_comment_underline);
		video_info_wrap.setVisibility(View.GONE);

		ImageView video_rotate = (ImageView) findViewById(R.id.video_rotate);
		video_rotate.setOnClickListener(videoRotateListener);

		// 카카오톡 전송
		ImageView btn_kkakkao = (ImageView) findViewById(R.id.btn_kakao);
		btn_kkakkao.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				try {

					if (event.getAction() == MotionEvent.ACTION_UP) {
						
						
//						Intent intent_joyhub= new Intent(getApplicationContext(),
//								JoyhubWebview.class);
//								intent_joyhub.putExtra("target_url", g_joyhub.getMainURL());
//								intent_joyhub.putExtra("main_url", g_joyhub.getMainURL());
//								intent_joyhub.putExtra("profile_url", g_joyhub.getAppProfileURL());
//								intent_joyhub.putExtra("shop_url", g_joyhub.getShopURL());
//								intent_joyhub.putExtra("setting_url", g_joyhub.getSettingURL());
//								startActivity(intent_joyhub);
						

						LayoutInflater inflater = (LayoutInflater) mActivity
								.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

						final View layout = inflater.inflate(
								R.layout.kakao_msg_box, (ViewGroup) mActivity
										.findViewById(R.id.folder_add_popup));
						AlertDialog.Builder aDialog = new AlertDialog.Builder(
								MainActivity.this);
						aDialog.setTitle("메시지를 입력해주세요");
						aDialog.setView(layout);
						aDialog.setPositiveButton("보내기",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										KakaoUtil kakaoUtil = new KakaoUtil(
												MainActivity.this);

										String cpostId = mCurplayItem
												.getCpost_id();
										String link = mCurplayItem.getLink();

										try {
											EditText kakao_msg_edittext = (EditText) layout
													.findViewById(R.id.kakao_message_edittext);
											String message = kakao_msg_edittext
													.getText().toString();

											// cid=[cpostId]&message=[message]
											StringBuffer webParam = new StringBuffer();
											webParam.append("link=");
											webParam.append(link);
											webParam.append("&message=");
											webParam.append(URLEncoder
													.encode(message));

											// &cid=[cpostId]&link=[youtubelink]
											StringBuffer execParam = new StringBuffer();
											execParam.append("&cid=");
											execParam.append(cpostId);
											execParam.append("&link=");
											execParam.append(link);

											// 보내기
											kakaoUtil.sendAppData(message,
													webParam.toString(),
													execParam.toString());

										} catch (NameNotFoundException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								});
						aDialog.setNegativeButton("취소",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
									}
								});
						AlertDialog ad = aDialog.create();

						EditText kakao_msg_edittext = (EditText) layout
								.findViewById(R.id.kakao_message_edittext);
						kakao_msg_edittext.setText("'"
								+ mCurplayItem.getTitle() + "'" + " 들어 보세요!!");

						ad.show();

					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				return true;
			}

		});

		// 페이스북 담벼락 글남기기
		ImageView btn_share_facebook = (ImageView) findViewById(R.id.btn_share_facebook);
		btn_share_facebook.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				try {

					if (event.getAction() == MotionEvent.ACTION_UP) {

						// fb login check
						if (!facebookMd.isActiveSession()) { // no facebook
																// login
							facebookMd.showLoginPage(new FacebookCallback() {

								@Override
								public void callback() {
									// TODO Auto-generated method stub
									SharedPreferences prefs = getSharedPreferences(
											FacebookMd.PREFERENCE_USER_KEY,
											Activity.MODE_PRIVATE);
									String fbId = prefs.getString(
											FacebookMd.PREFERENCE_USER_FB_ID,
											"");
									String fbFirstNm = prefs
											.getString(
													FacebookMd.PREFERENCE_USER_FB_FIRST_NM,
													"");
									String fbLastNm = prefs
											.getString(
													FacebookMd.PREFERENCE_USER_FB_LAST_NM,
													"");
									String email = prefs
											.getString(
													FacebookMd.PREFERENCE_USER_FB_LAST_EMAIL,
													"");
									facebookMd.requestGetUserId(fbId,
											fbFirstNm, fbLastNm, email,
											new FacebookMd.RequestCallback() {
												@Override
												public void callback(String msg) {
													// TODO Auto-generated
													// method stub
													if ("genreno".equals(msg)) { // 장르가
																					// 아직...세팅안된
																					// 회원
														userProfileMd
																.setProfileSavedCallback(new UserProfileMd.UserProfileCallback() {
																	@Override
																	public void callback() {
																		userProfileMd
																				.hideUserProfile();
																		folderMd.showFolderList();
																	}
																});
														facebookMd
																.hideLoginPage();
														userProfileMd
																.showUserProfile();

													} else { // 기존회원

														facebookMd
																.publishFeedDialog(mCurplayItem);
													}

												}
											});
								}
							});

						} else if (facebookMd.isActiveSession()
								&& facebookMd.getBonoUserId().length() < 1) { // facebook
																				// login
																				// but
																				// no
																				// userid
							SharedPreferences prefs = getSharedPreferences(
									FacebookMd.PREFERENCE_USER_KEY,
									Activity.MODE_PRIVATE);
							String fbId = prefs.getString(
									FacebookMd.PREFERENCE_USER_FB_ID, "");
							String fbFirstNm = prefs.getString(
									FacebookMd.PREFERENCE_USER_FB_FIRST_NM, "");
							String fbLastNm = prefs.getString(
									FacebookMd.PREFERENCE_USER_FB_LAST_NM, "");
							String email = prefs.getString(
									FacebookMd.PREFERENCE_USER_FB_LAST_EMAIL,
									"");

							facebookMd.requestGetUserId(fbId, fbFirstNm,
									fbLastNm, email,
									new FacebookMd.RequestCallback() {

										@Override
										public void callback(String msg) {
											// TODO Auto-generated method stub
											String userId = facebookMd
													.getBonoUserId();
											if (userId == null
													|| userId.length() < 1) {
												// 기존회원인데 장르 세팅 안된 회원
												userProfileMd
														.setProfileSavedCallback(new UserProfileMd.UserProfileCallback() {
															@Override
															public void callback() {
																userProfileMd
																		.hideUserProfile();
															}
														});
												userProfileMd.showUserProfile();
											} else {
												// 기존회원
												facebookMd
														.publishFeedDialog(mCurplayItem);

											}

										}
									});

						} else { // having ids
							facebookMd.publishFeedDialog(mCurplayItem);
						}

					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				return true;
			}

		});

	}

	OnTouchListener videoPreviewListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			ImageView view = (ImageView) v;
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				view.setPadding(2, 2, 2, 2);
				view.setColorFilter(0xaa111111, Mode.SRC_OVER);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				nextPrePlay();
				view.setPadding(0, 0, 0, 0);
				view.setColorFilter(0x00000000, Mode.SRC_OVER);
			}
			return false;
		}
	};

	OnTouchListener videoNextListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {

			ImageView view = (ImageView) v;
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				view.setPadding(2, 2, 2, 2);
				view.setColorFilter(0xaa111111, Mode.SRC_OVER);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				nextVideoPlay();
				view.setPadding(0, 0, 0, 0);
				view.setColorFilter(0x00000000, Mode.SRC_OVER);
			}
			return false;
		}
	};

	OnTouchListener videoPauseListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {

			ImageView view = (ImageView) v;
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				view.setPadding(2, 2, 2, 2);
				view.setColorFilter(0xaa111111, Mode.SRC_OVER);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {

				MyVideoView myVideoView = (MyVideoView) findViewById(R.id.surface);
				if (myVideoView.isPlaying()) {
					myVideoView.pause();
				} else {
					myVideoView.start();
				}

				view.setPadding(0, 0, 0, 0);
				view.setColorFilter(0x00000000, Mode.SRC_OVER);
			}
			return false;
		}
	};

	OnTouchListener videoLike = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {

			if (MediaPlayerSingleton.playMode == PlayBackService.REQUEST_DONE_GET_TEMP_VIDEO_TO_PLAY) {
				return true;
			}

			ImageView view = (ImageView) v;
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				view.setPadding(2, 2, 2, 2);
				view.setColorFilter(0xaa111111, Mode.SRC_OVER);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {

				// ImageView img = (ImageView)v;
				// if(MediaPlayerSingleton.repeatMode ==
				// MediaPlayerSingleton.PLAY_MODE_ONE_REPEAT){
				// img.setImageResource(R.drawable.btn_pepeatall);
				// MediaPlayerSingleton.repeatMode =
				// MediaPlayerSingleton.PLAY_MODE_REPEAT;
				// }else{
				// img.setImageResource(R.drawable.btn_repeatone);
				// MediaPlayerSingleton.repeatMode =
				// MediaPlayerSingleton.PLAY_MODE_ONE_REPEAT;
				// }

				// fb login check
				if (!facebookMd.isActiveSession()) { // no facebook login

					facebookMd.showLoginPage(new FacebookCallback() {

						@Override
						public void callback() {
							// TODO Auto-generated method stub
							SharedPreferences prefs = getSharedPreferences(
									FacebookMd.PREFERENCE_USER_KEY,
									Activity.MODE_PRIVATE);
							String fbId = prefs.getString(
									FacebookMd.PREFERENCE_USER_FB_ID, "");
							String fbFirstNm = prefs.getString(
									FacebookMd.PREFERENCE_USER_FB_FIRST_NM, "");
							String fbLastNm = prefs.getString(
									FacebookMd.PREFERENCE_USER_FB_LAST_NM, "");
							String email = prefs.getString(
									FacebookMd.PREFERENCE_USER_FB_LAST_EMAIL,
									"");
							facebookMd.requestGetUserId(fbId, fbFirstNm,
									fbLastNm, email,
									new FacebookMd.RequestCallback() {
										@Override
										public void callback(String msg) {
											// TODO Auto-generated method stub
											if ("genreno".equals(msg)) { // 장르가
																			// 아직...세팅안된
																			// 회원
												facebookMd.hideLoginPage();

												userProfileMd
														.setProfileSavedCallback(new UserProfileMd.UserProfileCallback() {
															@Override
															public void callback() {
																// MdManager.removeAllMd();
																requestLike();
															}
														});
											} else { // 기존회원
												requestLike();
											}
										}
									});
						}
					});
				} else if (facebookMd.isActiveSession()
						&& facebookMd.getBonoUserId().length() < 1) { // facebook
																		// login
																		// but
																		// no
																		// userid
					SharedPreferences prefs = getSharedPreferences(
							FacebookMd.PREFERENCE_USER_KEY,
							Activity.MODE_PRIVATE);
					String fbId = prefs.getString(
							FacebookMd.PREFERENCE_USER_FB_ID, "");
					String fbFirstNm = prefs.getString(
							FacebookMd.PREFERENCE_USER_FB_FIRST_NM, "");
					String fbLastNm = prefs.getString(
							FacebookMd.PREFERENCE_USER_FB_LAST_NM, "");
					String email = prefs.getString(
							FacebookMd.PREFERENCE_USER_FB_LAST_EMAIL, "");

					facebookMd.requestGetUserId(fbId, fbFirstNm, fbLastNm,
							email, new FacebookMd.RequestCallback() {

								@Override
								public void callback(String msg) {
									// TODO Auto-generated method stub

									if ("genreno".equals(msg)) { // 장르가
																	// 아직...세팅안된
																	// 회원
										facebookMd.hideLoginPage();

										userProfileMd
												.setProfileSavedCallback(new UserProfileMd.UserProfileCallback() {
													@Override
													public void callback() {
														// MdManager.removeAllMd();
														requestLike();
														// TextView
														// btn_top_right =
														// (TextView)
														// findViewById(R.id.btn_top_right_text);
														// btn_top_right.setText("studio");
													}
												});
									} else { // 기존회원
										requestLike();
									}

								}
							});

				} else { // having ids
					requestLike();
				}

				view.setPadding(0, 0, 0, 0);
				view.setColorFilter(0x00000000, Mode.SRC_OVER);

			}
			return false;
		}
	};

	public void requestLike() {
		if (mCurplayItem == null) {
			return;
		}

		int timeout = 2;
		new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {

			@Override
			public void fail(Object result) {
				// TODO Auto-generated method stub
				AlertDialog.Builder ab = new AlertDialog.Builder(
						MainActivity.this);
				ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");
				ab.setPositiveButton("ok", null);
				ab.show();
			}

			@Override
			public void sucess(Object result) {
				ImageView player_like_btn = (ImageView) findViewById(R.id.player_like_btn);
				if ("unlike".equals(result)) { // 좋아요 삭제
					player_like_btn.setImageResource(R.drawable.btn_likeoff);
					player_like_btn.setTag("0");
				} else { // 좋아요 하기
					player_like_btn.setImageResource(R.drawable.btn_likeon);
					player_like_btn.setTag("1");
					mCurplayItem.setIsLikeIdx("1");

				}
			}

			@Override
			public void threadProcess(ConnectThread resultset) throws Exception {
				// TODO Auto-generated method stub
				HttpClient client = NetWorkManager.getHttpConnection();
				HttpConnectionParams.setConnectionTimeout(client.getParams(),
						1000);

				HttpPost post = new HttpPost(
						"http://14.63.217.155/radio_bonosound/reqLike.php");

				// 2. parameter :
				// a. uId : 사용자ID
				// b. pUid : 포스트 올린 사용자 ID(취소시에만)
				// c. cId : 포스트 ID

				String uId = facebookMd.getBonoUserId();
				String pUid = mCurplayItem.getpUid();
				String cId = mCurplayItem.getCpost_id();

				List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();

				ImageView player_like_btn = (ImageView) findViewById(R.id.player_like_btn);

				if ("1".equals(player_like_btn.getTag())) { // 좋아요 삭제하기
					params.add(new BasicNameValuePair("type", "2"));
					params.add(new BasicNameValuePair("uId", uId));
					params.add(new BasicNameValuePair("cId", cId));
					params.add(new BasicNameValuePair("pUid", pUid));
				} else { // 좋아요 하기
					params.add(new BasicNameValuePair("type", "1"));
					params.add(new BasicNameValuePair("uId", uId));
					params.add(new BasicNameValuePair("cId", cId));
				}

				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,
						HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);

				InputStream in = responsePOST.getEntity().getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(in));
				StringBuilder str = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					str.append(line);
				}
				in.close();
				String jsonStr = str.toString();

				if ("1".equals(player_like_btn.getTag())) { // 좋아요 삭제하기
					resultset.setResult("unlike");
				} else { // 좋아요 하기
					resultset.setResult("like");
				}

			}
		}).start();
	}

	OnTouchListener topTouchListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			ImageView view = (ImageView) v;
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				view.setPadding(2, 2, 2, 2);
				view.setColorFilter(0xaa111111, Mode.SRC_OVER);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				// toggleGenreList();
				view.setPadding(0, 0, 0, 0);
				view.setColorFilter(0x00000000, Mode.SRC_OVER);
			}
			return false;
		}
	};

	OnClickListener videoRotateListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int orientation = getResources().getConfiguration().orientation;

			if (orientation == Configuration.ORIENTATION_PORTRAIT) {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			} else {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			}
		}
	};

	OnTouchListener videoOwnerTouchListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {

			if (event.getAction() == MotionEvent.ACTION_DOWN) {

			} else if (event.getAction() == MotionEvent.ACTION_UP) {

				AlertDialog.Builder alt_bld = new AlertDialog.Builder(
						MainActivity.this);
				alt_bld.setMessage(
						"Would you like to listen to more songs from this DJ?")
						.setCancelable(false)
						.setPositiveButton("Yes",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										// Action for 'Yes' Button
										try {
											m_LoadingProgress
													.setVisibility(View.VISIBLE);
											Message msgForSend = Message
													.obtain(null,
															PlayBackService.REQUEST_MSG_GET_USER_PLAYLIST);
											msgForSend.replyTo = mMessenger;
											mService.send(msgForSend);
										} catch (Exception e) {
											e.printStackTrace();
										}
									}
								})
						.setNegativeButton("No",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										// Action for 'NO' Button
										dialog.cancel();
									}
								});
				AlertDialog alert = alt_bld.create();
				alert.setTitle(" More Music!!");
				alert.show();

			}
			return false;
		}
	};

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			mOrientation = newConfig.orientation;
			showLandscapeView();

		} else {
			mOrientation = newConfig.orientation;
			showPortraitView();
		}
	}

	public void showLandscapeView() {
		try {
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			ImageView imageView = (ImageView) findViewById(R.id.img_genre_top);
			imageView.setVisibility(View.GONE);

			FrameLayout player_buttons = (FrameLayout) findViewById(R.id.player_buttons);
			player_buttons.setVisibility(View.GONE);

			if (mCurMoudle != null) {
				mCurMoudle.hide();
			}

			FrameLayout videoWrap = (FrameLayout) findViewById(R.id.video_wrap);
			MediaPlayerSingleton.videoWrapWidth = videoWrap.getWidth();
			MediaPlayerSingleton.videoWrapHeight = videoWrap.getHeight();

			WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
			Display display = wm.getDefaultDisplay();

			videoWrap.setLayoutParams(new LinearLayout.LayoutParams(display
					.getWidth(), display.getHeight()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void showPortraitView() {
		try {
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			ImageView imageView = (ImageView) findViewById(R.id.img_genre_top);
			imageView.setVisibility(View.VISIBLE);

			FrameLayout player_buttons = (FrameLayout) findViewById(R.id.player_buttons);
			player_buttons.setVisibility(View.VISIBLE);

			FrameLayout videoWrap = (FrameLayout) findViewById(R.id.video_wrap);
			videoWrap.setLayoutParams(new LinearLayout.LayoutParams(
					MediaPlayerSingleton.videoWrapWidth,
					MediaPlayerSingleton.videoWrapHeight));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// =========================================================================================================
	// SERVICE Stuff
	// =========================================================================================================
	public void doBindService() {
		bindService(new Intent(this, PlayBackService.class), mConnection,
				Context.BIND_AUTO_CREATE);
	}

	public final Messenger mMessenger = new Messenger(new IncomingHandler());
	public Messenger mService = null;

	public void sendMessageToService(Message msg) {
		msg.replyTo = mMessenger;
		try {
			if (mService != null) {
				mService.send(msg);
			}
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@SuppressLint("HandlerLeak")
	class IncomingHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			PlayItem playItem = null;
			Message msgForSend = null;
			try {
				switch (msg.what) {
				case PlayBackService.REQUEST_DONE_BONO_PLAYLIST:
					msgForSend = Message.obtain(null,
							PlayBackService.REQUEST_MSG_GET_VIDEO_TO_PLAY);
					msgForSend.replyTo = mMessenger;
					msgForSend.arg1 = 1;
					mService.send(msgForSend);
					break;

				case PlayBackService.REQUEST_DONE_GET_VIDEO_INFO:
					MediaPlayerSingleton.playMode = PlayBackService.REQUEST_DONE_GET_VIDEO_INFO;
					playItem = (PlayItem) msg.obj;
					mCurplayItem = playItem;

					displayPlayVideoInfo(playItem);
					break;

				case PlayBackService.REQUEST_DONE_GET_VIDEO_TO_PLAY:
					MediaPlayerSingleton.playMode = PlayBackService.REQUEST_DONE_GET_VIDEO_TO_PLAY;
					playItem = (PlayItem) msg.obj;
					mCurplayItem = playItem;
					if (playItem != null) {

						displayPlayVideoInfo(playItem);

						View btn_kakao = findViewById(R.id.btn_kakao);
						btn_kakao.setVisibility(View.VISIBLE);

						View btn_share_facebook = findViewById(R.id.btn_share_facebook);
						btn_share_facebook.setVisibility(View.VISIBLE);

						if ("3g".equals(MediaPlayerSingleton.whatKindOfNetwork)) {
							playVideo(playItem.getLowQualityUrl());
						} else {
							playVideo(playItem.getHighQualityUrl());
						}

					}
					break;

				case PlayBackService.REQUEST_DONE_GET_TEMP_VIDEO_TO_PLAY:
					playItem = (PlayItem) msg.obj;
					if (playItem == null
							|| (playItem.getLowQualityUrl() == null && playItem
									.getHighQualityUrl() == null)) {
						AlertDialog.Builder ab = new AlertDialog.Builder(
								MainActivity.this);
						ab.setMessage("재생할 수 없는 동영상 입니다.");
						ab.setPositiveButton("ok", null);
						ab.show();
					} else {
						// 현재 모드
						MediaPlayerSingleton.playMode = PlayBackService.REQUEST_DONE_GET_TEMP_VIDEO_TO_PLAY;

						if ("3g".equals(MediaPlayerSingleton.whatKindOfNetwork)) {
							playVideo(playItem.getLowQualityUrl());
						} else {
							playVideo(playItem.getHighQualityUrl());
						}
						playItem.setFirst_name("유튜브 임시 플레이");
						playItem.setLast_name("");
						playItem.setLikeCnt("0");

						View btn_kakao = findViewById(R.id.btn_kakao);
						btn_kakao.setVisibility(View.GONE);

						View btn_share_facebook = findViewById(R.id.btn_share_facebook);
						btn_share_facebook.setVisibility(View.GONE);

						displayPlayVideoInfo(playItem);
					}
					break;
				case PlayBackService.REQUEST_DONE_GET_KAKAO_VIDEO_TO_PLAY:
					playItem = (PlayItem) msg.obj;
					if (playItem == null
							|| (playItem.getLowQualityUrl() == null && playItem
									.getHighQualityUrl() == null)) {
						AlertDialog.Builder ab = new AlertDialog.Builder(
								MainActivity.this);
						ab.setMessage("재생할 수 없는 동영상 입니다.");
						ab.setPositiveButton("ok", null);
						ab.show();
					} else {
						if ("3g".equals(MediaPlayerSingleton.whatKindOfNetwork)) {
							playVideo(playItem.getLowQualityUrl());
						} else {
							playVideo(playItem.getHighQualityUrl());
						}

						View btn_kakao = findViewById(R.id.btn_kakao);
						btn_kakao.setVisibility(View.VISIBLE);

						View btn_share_facebook = findViewById(R.id.btn_share_facebook);
						btn_share_facebook.setVisibility(View.VISIBLE);

						displayPlayVideoInfo(playItem);
					}
					break;

				case PlayBackService.REQUEST_DONE_MSG_GET_CURRENT_POSITION:
					playItem = (PlayItem) msg.obj;
					int seekTo = msg.arg1;

					if (playItem != null) {
						if ("3g".equals(MediaPlayerSingleton.whatKindOfNetwork)) {
							keepPlayVideo(playItem.getHighQualityUrl(), seekTo);
						} else {
							keepPlayVideo(playItem.getLowQualityUrl(), seekTo);
						}
					}
					break;

				default:
					super.handleMessage(msg);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			mService = new Messenger(service);
			// Log.e("onServiceConnected", "onServiceConnected");
			// try {
			//
			// } catch (RemoteException e) {
			// // In this case the service has crashed before we could even do
			// anything with it
			// }

			// 카카오톡에서 보낸거면 플레이
			kakaoPlay();
		}

		public void onServiceDisconnected(ComponentName className) {
			// This is called when the connection with the service has been
			// unexpectedly disconnected - process crashed.
			mService = null;
		}
	};

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.video_wrap) {
			return;
		}

		// channelMd.onClick(v, mMessenger, mService);
		genreMd.onClick(v, mMessenger, mService);
		m_LoadingProgress.setVisibility(View.VISIBLE);
	}

	long startTimeInterVal = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			if (keyCode == KeyEvent.KEYCODE_BACK) {
				// return super.onKeyDown(keyCode, event);
				if (startTimeInterVal != 0
						&& System.currentTimeMillis() - startTimeInterVal < 2000) {
					return super.onKeyDown(keyCode, event);
				} else {

					if (mCurMoudle != null && mCurMoudle.isVisible()) {
						mCurMoudle.back();
					} else if (mCurMoudle != null && !mCurMoudle.isVisible()) {
						mCurMoudle.show();
					} else {
						startTimeInterVal = System.currentTimeMillis();
						// Toast.makeText(getApplicationContext(),
						// "Please tap the Back button once more to close this app!",
						// Toast.LENGTH_SHORT).show();
						Toast.makeText(getApplicationContext(),
								"'뒤로'버튼을 한번 더 누르시면 종료됩니다", Toast.LENGTH_SHORT)
								.show();
					}
				}
				return false;
			}
		}

		if (keyCode == KeyEvent.KEYCODE_MENU) {
			// if(studio_layout.getVisibility() == View.VISIBLE){
			// studio_layout.setVisibility(View.GONE);
			// }else{
			// showGenreList();
			// }
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onResume() {
		doBindService();
		super.onResume();
		facebookMd.onResume();

		MyVideoView myVideoView = (MyVideoView) findViewById(R.id.surface);
		myVideoView.setOnPreparedListener(this);
		myVideoView.setOnCompletionListener(this);
		myVideoView.setOnBufferingUpdateListener(this);
		// myVideoView.setOnInfoListener(this);
		myVideoView.setOnErrorListener(this);
		myVideoView.setOnSeekCompleteListener(this);
		myVideoView.playOnForground();

		Bundle bundle = getIntent().getExtras();

		if (bundle != null) {
			kakaoPlay();
		} else if (MediaPlayerSingleton.playMode == PlayBackService.REQUEST_DONE_GET_VIDEO_TO_PLAY) {

			Message msg = Message.obtain(null,
					PlayBackService.REQUEST_MSG_GET_VIDEO_INFO);
			sendMessageToService(msg);

			View btn_kakao = findViewById(R.id.btn_kakao);
			btn_kakao.setVisibility(View.VISIBLE);

			View btn_share_facebook = findViewById(R.id.btn_share_facebook);
			btn_share_facebook.setVisibility(View.VISIBLE);
		}

		// 앱이 화면으로 돌아왔다네
		PlayBackService.displayMode = PlayBackService.PLAY_FROEGRUND;		
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		facebookMd.onSaveInstanceState(outState);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		doBindService();
		super.onNewIntent(intent);
		setIntent(intent);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		try {
			Message msgForSend = Message.obtain(null,
					PlayBackService.SETTING_PLAYBACK_MODE);

			if (mService != null) {
				mService.send(msgForSend);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onStop();
		facebookMd.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		mNotificationManager.cancel(1234567890);
		stopService(new Intent("com.ideabove.service.PlayBackService"));
		unbindService(mConnection);
		unregisterToken();
		super.onDestroy();
		facebookMd.onDestroy();
	}

	private void playVideo(String url) {
		m_LoadingProgress.setVisibility(View.VISIBLE);

		MyVideoView myVideoView = (MyVideoView) findViewById(R.id.surface);
		myVideoView.setOnPreparedListener(this);
		myVideoView.setOnCompletionListener(this);
		myVideoView.setOnBufferingUpdateListener(this);
		// myVideoView.setOnInfoListener(this);
		myVideoView.setOnErrorListener(this);
		myVideoView.setOnSeekCompleteListener(this);
		myVideoView.setVideoURI(Uri.parse(url));
		myVideoView.setMediaController(new MyMediaController(this)
				.setOnMediaControllerToggle(this));
		myVideoView.requestFocus();
		myVideoView.start();
		System.gc();
	}

	private void keepPlayVideo(String url, int seekto) {
		m_LoadingProgress.setVisibility(View.VISIBLE);

		MyVideoView myVideoView = (MyVideoView) findViewById(R.id.surface);
		myVideoView.setOnPreparedListener(this);
		myVideoView.setOnCompletionListener(this);
		myVideoView.setOnBufferingUpdateListener(this);
		myVideoView.setOnErrorListener(this);
		myVideoView.setOnSeekCompleteListener(this);
		myVideoView.setVideoURI(Uri.parse(url));
		myVideoView.setMediaController(new MyMediaController(this)
				.setOnMediaControllerToggle(this));
		myVideoView.requestFocus();
		myVideoView.start();
		System.gc();
	}

	private void displayPlayVideoInfo(PlayItem playItem) {
		video_info_wrap.setVisibility(View.VISIBLE);
		video_title.setText(playItem.getTitle());
		video_owner.setText(playItem.getFirst_name() + " "
				+ playItem.getLast_name());
		// video_link_cnt.setText("Like · " + playItem.getLikeCnt());
		video_desc.setText(playItem.getPost());

		ImageView player_like_btn = (ImageView) findViewById(R.id.player_like_btn);

		if (playItem.getIsLikeIdx() != null) {
			int likeCnt = Integer.parseInt(playItem.getIsLikeIdx());
			if (likeCnt < 1) {
				player_like_btn.setImageResource(R.drawable.btn_likeoff);
				player_like_btn.setTag("0");
			} else {
				player_like_btn.setImageResource(R.drawable.btn_likeon);
				player_like_btn.setTag("1");
			}

			if (playItem.getComments() != null
					&& playItem.getComments().size() > 0) {
				video_comments.setVisibility(View.VISIBLE);
				list_comment_underline.setVisibility(View.VISIBLE);

				ArrayList<Comment> commentArr = (ArrayList<Comment>) playItem
						.getComments();
				ListAdapter adapter = new CommentAdapter(
						getApplicationContext(), commentArr);
				video_comments.setAdapter(adapter);
			} else {
				video_comments.setVisibility(View.GONE);
				list_comment_underline.setVisibility(View.GONE);

			}
		} else {
			list_comment_underline.setVisibility(View.GONE);
		}
	}

	@Override
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		// TODO Auto-generated method stub
		if (mp.isPlaying() && MediaPlayerSingleton.percent < percent + 5) {
			m_LoadingProgress.setVisibility(View.GONE);
		}
	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		removeLoadingBar();
		MediaPlayerSingleton.whatKindOfNetwork = Connectivity
				.getWhatKindOfNetwork(getApplicationContext());
		showNotification();
	}

	public void showNotification() {

		// Notification and intent of the notification
		Notification notification = new Notification(R.drawable.nofify_25, "",
				System.currentTimeMillis());
		notification.flags = Notification.FLAG_ONGOING_EVENT;

		Intent mainIntent = new Intent(getBaseContext(), MainActivity.class);
		PendingIntent pendingMainIntent = PendingIntent.getActivity(
				getBaseContext(), 0, mainIntent, 0);
		notification.contentIntent = pendingMainIntent;

		// Remoteview and intent for my button
		RemoteViews notificationView = new RemoteViews(getBaseContext()
				.getPackageName(), R.layout.remote_view_layout);

		Intent activityIntent = new Intent(Intent.ACTION_CALL,
				Uri.parse("tel:190"));
		PendingIntent pendingLaunchIntent = PendingIntent.getActivity(
				getBaseContext(), 0, activityIntent,
				PendingIntent.FLAG_UPDATE_CURRENT);

		notificationView.setOnClickPendingIntent(R.id.move_bonoradio,
				pendingLaunchIntent);

		notification.contentView = notificationView;

		NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		notificationManager.notify(1234567890, notification);
	}

	@Override
	public void onCompletion(MediaPlayer mp) {

		if (MediaPlayerSingleton.playMode == MediaPlayerSingleton.PLAY_MODE_ONE_REPEAT) {
			removeLoadingBar();
			repeatVideoPlay();
		} else {
			removeLoadingBar();
			nextVideoPlay();
		}

	}

	public void removeLoadingBar() {
		m_LoadingProgress.setVisibility(View.GONE);
	}

	public synchronized void nextVideoPlay() {
		try {
			m_LoadingProgress.setVisibility(View.VISIBLE);
			Message msgForSend = Message.obtain(null,
					PlayBackService.REQUEST_MSG_GET_NEXT_VIDEO_TO_PLAY);
			msgForSend.replyTo = mMessenger;
			msgForSend.arg1 = 1;
			mService.send(msgForSend);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void repeatVideoPlay() {
		try {
			m_LoadingProgress.setVisibility(View.VISIBLE);
			Message msgForSend = Message.obtain(null,
					PlayBackService.REQUEST_MSG_GET_REPEAT_VIDEO_TO_PLAY);
			msgForSend.replyTo = mMessenger;
			msgForSend.arg1 = 1;
			mService.send(msgForSend);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public synchronized void nextPrePlay() {
		try {
			m_LoadingProgress.setVisibility(View.VISIBLE);
			Message msgForSend = Message.obtain(null,
					PlayBackService.REQUEST_MSG_GET_PRE_VIDEO_TO_PLAY);
			msgForSend.replyTo = mMessenger;
			msgForSend.arg1 = 1;
			mService.send(msgForSend);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {

		if (mp.isPlaying()) {
			repeatVideoPlay();
		} else {
			nextPrePlay();
		}

		return false;
	}

	@Override
	public void onSeekComplete(MediaPlayer mp) {
		// int seconds = (int) (mp.getCurrentPosition() / 1000) % 60;

		// Log.e("###", "##" + MediaPlayerSingleton.whatKindOfNetwork);
		if (!MediaPlayerSingleton.whatKindOfNetwork.equals(Connectivity
				.getWhatKindOfNetwork(getApplicationContext()))) {
			nextPrePlay();
		}

		m_LoadingProgress.setVisibility(View.VISIBLE);
		MediaPlayerSingleton.percent = (100 * mp.getCurrentPosition())
				/ mp.getDuration();
	}

	@Override
	public void onMediaControllerToggle(boolean isShowing) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onInfo(MediaPlayer mp, int what, int extra) {
		// TODO Auto-generated method stub
		return false;
	}

}
